package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.BlxxService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: IEIS2-COM
 * @Package: com.indusfo.spc.service.impl
 * @ClassName: BlxxServiceImpl
 * @Author: 熊冰
 * @Description: 不良现象 业务层
 * @Date: 2019/8/20 15:53
 * @Version: 1.0
 */
@Service
public class BlxxServiceImpl implements BlxxService {
    //日志记录
    private static final Logger logger = LoggerFactory.getLogger(BlxxServiceImpl.class);

    @Autowired
    private BlxxMapper blxxMapper;
    @Autowired
    private BlxxtypeMapper blxxtypeMapper;
    @Autowired
    private BlxxProMapper blxxProMapper;

    //查询
    @Override
    public JSONObject listBlxx(Blxx blxx) {

        try {

            // 获取一页显示多少行
            Integer pagesize = blxx.getPagesize();
            // 获取查询第几页
            Integer pageindex = blxx.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                blxx.setIncept(pagesize * (pageindex - 1));
            }
            Integer blxxtypeId = null;
            if (blxx.getBadphenoTypeId() != null) {
                blxxtypeId = blxx.getBadphenoTypeId();
            }
            //是否有类型
            System.out.println(blxxtypeId);
            //无类型查询第一个类型数据
            if (blxxtypeId == null) {
                //获取第一个数据
                Blxxtype blxxtype = new Blxxtype();
                blxxtype.setBadphenoTypePid(0);
                List<Blxxtype> blxxtypeList = blxxtypeMapper.selectAllBlxxtype(blxxtype);
                if (blxxtypeList != null && blxxtypeList.size() >= 1) {
                    blxxtype = blxxtypeList.get(0);
                }
                //生成树
                //查询全部
                List<Blxxtype> list = blxxtypeMapper.selectAllBlxxtype(new Blxxtype());
                List<XTreeNode> treelist = new ArrayList<>();
                //将树放入list
                for (Blxxtype _MouldType : list) {
                    XTreeNode node = new XTreeNode();
                    node.setId(_MouldType.getBadphenoTypeId());
                    node.setpId(_MouldType.getBadphenoTypePid());
                    node.setTitle(_MouldType.getBadphenoTypeName());
                    treelist.add(node);
                }
                //获取子类
                XTreeUtil xTreeUtil = new XTreeUtil(blxxtype.getBadphenoTypeId(), treelist);
                List<Integer> childs=xTreeUtil.getChilds();
                List<Blxx> listForPage = blxxMapper.queryListBlxx(blxx, childs);
                Integer count = blxxMapper.countListBlxx(blxx, childs);
                return JSONObject.oK(listForPage, count);

            } else {

                if (blxxtypeId == 0) {
                    //全查
                    blxx.setBadphenoTypeId(null);
                    List<Blxx> listForPage = blxxMapper.selectAllBlxx(blxx);
                    if (pagesize != null && pageindex != null) {
                        Integer count = blxxMapper.countBlxx(blxx);
                        return JSONObject.oK(listForPage, count);
                    }else{
                        return JSONObject.oK(listForPage.get(0));
                    }

                } else {

                    List<Blxxtype> list = blxxtypeMapper.selectAllBlxxtype(new Blxxtype());
                    List<XTreeNode> treelist = new ArrayList<>();
                    for (Blxxtype _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getBadphenoTypeId());
                        node.setpId(_MouldType.getBadphenoTypePid());
                        node.setTitle(_MouldType.getBadphenoTypeName());
                        treelist.add(node);
                    }
                    XTreeUtil xTreeUtil = new XTreeUtil(blxxtypeId, treelist);
                    List<Integer>   childs=xTreeUtil.getChilds();
                    List<Blxx> listForPage = blxxMapper.queryListBlxx(blxx, childs);
                    Integer count = blxxMapper.countListBlxx(blxx, childs);
                    return JSONObject.oK(listForPage, count);
                }
            }
        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //新增
    @Override
    public JSONObject insertOrUpdateBlxx(Blxx blxx) {
        try {

            if (blxx.getBadphenoTypeId() == null) {
                blxx.setBadphenoTypeId(0);
            }
            if (blxx.getDataState() == null) {
                blxx.setDataState(1);
            }

            JSONObject checkParamsNotRepeatJson = checkParamsNotRepeat(blxx);
            if (checkParamsNotRepeatJson.isOk()) {

                if (blxx.getBadphenoId() != null) {// 有id,做更新
                    validate(blxx);
                    Integer row = blxxMapper.updateByPrimaryKeySelective(blxx);
                    if (row == 0) {
                        throw new ModifyFailedException("更新不良现象失败！");
                    }
                    return JSONObject.oK("更新成功！", row);
                } else {// 没id,做新增
                    // 校验传入参数
                    validate(blxx);
                    Integer row = blxxMapper.insertSelective(blxx);
                    if (row == 0) {
                        throw new ModifyFailedException("新增不良现象失败！");
                    }
                    return JSONObject.oK("新增成功！", row);
                }

            } else {
                throw new ParamsErrorException(checkParamsNotRepeatJson.getMsg());
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //删除
    @Override
    public JSONObject deleteBlxx(Long[] deteBlxx, Integer lDataState) {
        try {
            //1.校验
            if (deteBlxx == null) {
                throw new ParamsErrorException("不良现象id不能为空");
            }
            if (lDataState == null) {
                throw new ParamsErrorException("不良现象状态不能为空");
            }
            int row = blxxMapper.deleteBlxx(deteBlxx, lDataState);
            String msg = "";
            switch (lDataState) {
                case 1:
                    msg = "启用";
                    break;
                case 2:
                    msg = "删除";
                    break;
                case 3:
                    msg = "停用";
            }

            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (lDataState) {
                    case 1:
                        throw new ModifyFailedException(msg + "失败!");
                    case 2:
                        throw new ModifyFailedException(msg + "失败!");
                    case 3:
                        throw new ModifyFailedException(msg + "失败!");
                }
            }
            return JSONObject.oK(msg + "成功！", row);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    //添加不良原因
    @Override
    public JSONObject insertBlxxBlyy(Long[] ids, Integer blxxId) {
        try {
            if (blxxId == null || blxxId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = blxxMapper.insertBlxxBlyy(ids, blxxId);
                return JSONObject.oK("新增成功！", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    //删除不良原因
    @Override
    public JSONObject delBlxxBlyy(Long[] ids, Integer blxxId) {
        try {
            if (blxxId == null || blxxId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = blxxMapper.delBlxxBlyy(ids, blxxId);
                return JSONObject.oK("删除成功！", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    //添加不良对策
    @Override
    public JSONObject insertBlxxBldc(Long[] ids, Integer blxxId) {
        try {
            if (blxxId == null || blxxId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = blxxMapper.insertBlxxBldc(ids, blxxId);
                return JSONObject.oK("新增成功！", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    //删除不良对策
    @Override
    public JSONObject delBlxxBldc(Long[] ids, Integer blxxId) {
        try {
            if (blxxId == null || blxxId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = blxxMapper.delBlxxBldc(ids, blxxId);
                return JSONObject.oK("删除成功！", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    //查询不良原因关联
    @Override
    public JSONObject selectBlxxBlyy(Blxx blxx) {
        try {
            // 获取一页显示多少行
            Integer pagesize = blxx.getPagesize();
            // 获取查询第几页
            Integer pageindex = blxx.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                blxx.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法
            List<Blyy> listForPage = blxxMapper.selectBlxxBlyy(blxx);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有相关数据",listForPage, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count = blxxMapper.countBlxxBlyy(blxx);
                return JSONObject.oK("查询成功",listForPage, count);
            }
            return JSONObject.oK("查询成功",listForPage.get(0),1);

        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }
    //查询不良对策关联
    @Override
    public JSONObject selectBlxxBldc(Blxx blxx) {
        try {
            // 获取一页显示多少行
            Integer pagesize = blxx.getPagesize();
            // 获取查询第几页
            Integer pageindex = blxx.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                blxx.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法
            List<Bldc> listForPage = blxxMapper.selectBlxxBldc(blxx);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有相关数据",listForPage, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count = blxxMapper.countBlxxBldc(blxx);
                return JSONObject.oK("查询成功",listForPage, count);
            }
            return JSONObject.oK("查询成功",listForPage.get(0),1);

        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }
    //全查不良对策
    @Override
    public JSONObject queryBldc(Blxx blxx) {
//        List<Bldc> listBlxxBldc = null;
        List<Bldc> listBldc = null;
        try {
            // 获取一页显示多少行
            Integer pagesize = blxx.getPagesize();
            // 获取查询第几页
            Integer pageindex = blxx.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                blxx.setIncept(pagesize * (pageindex - 1));
            }

            if (blxx.getBadphenoId() != null) {  //如果有不良对策id,则查询单个不良对策
                //不良现象已有数据
                listBldc = blxxMapper.queryBldc(blxx);
                System.out.println(blxx.getPageindex()+"+"+blxx.getPagesize());
            } else {
                throw new ParamsErrorException("不良现象ID不能为空!");
            }

            //查询分页总记录数
            int count = blxxMapper.countBldc(blxx); //返回查询到的总记录数
            if (listBldc.isEmpty()) {
                return JSONObject.oK("没有不良对策相关数据", listBldc, count);
            }
            return JSONObject.oK("查询成功", listBldc, count);

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    //全查不良原因
    @Override
    public JSONObject queryBlyy(Blxx blxx) {
//        List<Blyy> listBlxxBlyy = null;
        List<Blyy> listBlyy = null;
        try {

            // 获取一页显示多少行
            Integer pagesize = blxx.getPagesize();
            // 获取查询第几页
            Integer pageindex = blxx.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                blxx.setIncept(pagesize * (pageindex - 1));
            }
            if (blxx.getBadphenoId() != null) {  //如果有不良对策id,则查询单个不良对策
                //不良现象已有数据
                listBlyy = blxxMapper.queryBlyy(blxx);

            } else {
                throw new ParamsErrorException("不良现象ID不能为空!");
            }

            //查询分页总记录数
            int count = blxxMapper.countBlyy(blxx);  //返回查询到的总记录数
            if (listBlyy.isEmpty()) {
                return JSONObject.oK("没有不良对策相关数据", listBlyy, count);
            }
            return JSONObject.oK("查询成功", listBlyy, count);

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject queryPro(BlxxPro blxxPro) {
        try {
            // 获取一页显示多少行
            Integer pagesize = blxxPro.getPagesize();
            // 获取查询第几页
            Integer pageindex = blxxPro.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                blxxPro.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法
            if (blxxPro.getBadphenoId() == null || blxxPro.getBadphenoId() == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            }
            List<BlxxPro> listForPage = blxxProMapper.selectPro(blxxPro);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有相关数据",listForPage, 0);
            }
            // 查询有多少条数据条数
            Integer count = blxxProMapper.countPro(blxxPro);
            return JSONObject.oK("查询成功",listForPage, count);
        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }

    }

    @Override
    public JSONObject insertPro(Long[] ids, Integer blxxId) {
        try {
            if (blxxId == null || blxxId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = blxxProMapper.insertPro(ids, blxxId);
                return JSONObject.oK("新增成功！", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    @Override
    public JSONObject delPro(Long[] ids) {
        try {
            int row = blxxProMapper.delPro(ids);
            return JSONObject.oK("删除成功！", row);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }


    //验证重复
    private JSONObject checkParamsNotRepeat(Blxx blxx) {
        try {
            // 判断不良原因类型ID是否传入
            if (blxx.getBadphenoTypeId() == null || blxx.getBadphenoTypeId() == 0) {
                throw new ParamsErrorException("未传入不良原因ID");
            } else {

                Blxx check = new Blxx();
                check.setBadphenoName(blxx.getBadphenoName());
                if (blxx.getBadphenoId() != null) {
                    // 有SOP基础资料ID为更新操作,调用剔除本条记录是否有重复
                    check.setBadphenoId(blxx.getBadphenoId());
                    int row = blxxMapper.countParamsNotRepeat(check);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品!");
                    }
                } else {

                    int row = blxxMapper.countParamsNotRepeat(check);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品!");
                    }
                }
                return JSONObject.oK();
            }

        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }


    //非空判断
    private void validate(Blxx blxx) {
        //现象名称
        String blxxName = blxx.getBadphenoName();

        if (StringUtils.isEmpty(blxxName)) {
            throw new ParamsErrorException("名称不能为空");
        }
        if (blxxName.getBytes().length > 50){
            throw new ParamsErrorException("不良现象名称过长");
        }
        String remark = blxx.getRemark();
        if(remark!=null) {
            if (remark.getBytes().length > 100) {
                throw new ParamsErrorException("说明过长");
            }
        }
        //类型id
        Integer blxxtypeid = blxx.getBadphenoTypeId();
        if(blxxtypeid == null){
            throw new ParamsErrorException("不良原因类型不能为空");
        }



    }
}
